import matplotlib.pyplot as plt
import numpy as np
import math

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

# 参数设置
principal = 1000       # 初始本金1000元
annual_rate = 0.05     # 年利率5%
years = 10             # 投资10年

# 计算不同复利频率的结果
frequencies = ['年复利', '半年复利', '季复利', '月复利', '周复利', '日复利', '连续复利']
results = []

# 年复利
result_annual = principal * (1 + annual_rate) ** years
results.append(result_annual)

# 半年复利
result_semi = principal * (1 + annual_rate/2) ** (years*2)
results.append(result_semi)

# 季复利
result_quarter = principal * (1 + annual_rate/4) ** (years*4)
results.append(result_quarter)

# 月复利
result_monthly = principal * (1 + annual_rate/12) ** (years*12)
results.append(result_monthly)

# 周复利
result_weekly = principal * (1 + annual_rate/52) ** (years*52)
results.append(result_weekly)

# 日复利
result_daily = principal * (1 + annual_rate/365) ** (years*365)
results.append(result_daily)

# 连续复利
result_continuous = principal * math.exp(annual_rate * years)
results.append(result_continuous)

# 绘制结果
plt.figure(figsize=(14, 6))

plt.subplot(1, 2, 1)
x_pos = np.arange(len(frequencies))
plt.bar(x_pos, results)
plt.xticks(x_pos, frequencies, rotation=45)
plt.ylabel('最终金额 (元)')
plt.title('不同复利频率下的投资增长')
for i, v in enumerate(results):
    plt.text(i, v, f'{v:.2f}', ha='center', va='bottom')

plt.subplot(1, 2, 2)
# 绘制连续复利增长曲线
time_points = np.linspace(0, years, 1000)
continuous_growth = principal * np.exp(annual_rate * time_points)

# 对比年复利
annual_points = []
for t in time_points:
    if t == 0:
        annual_points.append(principal)
    else:
        # 年复利在整数年计算
        full_years = int(t)
        partial_year = t - full_years
        base = principal * (1 + annual_rate) ** full_years
        if partial_year > 0:
            # 线性近似部分年的增长
            annual_points.append(base * (1 + annual_rate * partial_year))
        else:
            annual_points.append(base)

plt.plot(time_points, continuous_growth, 'r-', linewidth=2, label='连续复利')
plt.plot(time_points, annual_points, 'b--', linewidth=2, label='年复利')
plt.xlabel('时间 (年)')
plt.ylabel('金额 (元)')
plt.title('连续复利 vs 年复利增长曲线')
plt.legend()
plt.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()